package com.haier.dreambox.demo.persistence;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.haier.dreambox.demo.bean.uplus.*;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**
 * Created by smalant on 14/12/31.
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    private static final String DATABASE_NAME = "dreamBox.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TAG = DatabaseHelper.class.getSimpleName();

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, DeviceAttribute.class);
            TableUtils.createTable(connectionSource, DeviceType.class);
            TableUtils.createTable(connectionSource, DeviceStatus.class);
            TableUtils.createTable(connectionSource, DeviceVersion.class);
            TableUtils.createTable(connectionSource, DeviceLocation.class);
            TableUtils.createTable(connectionSource, SmartLinkVersion.class);
            TableUtils.createTable(connectionSource, Device.class);
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(TAG, "Unable to create database", e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource, DeviceAttribute.class, true);
            TableUtils.dropTable(connectionSource, DeviceType.class, true);
            TableUtils.dropTable(connectionSource, DeviceStatus.class, true);
            TableUtils.dropTable(connectionSource, DeviceVersion.class, true);
            TableUtils.dropTable(connectionSource, DeviceLocation.class, true);
            TableUtils.dropTable(connectionSource, SmartLinkVersion.class, true);
            TableUtils.dropTable(connectionSource, Device.class, true);
            onCreate(sqLiteDatabase, connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
            Log.e(TAG, "Unable to update database", e);
        }

    }


}
